#!/usr/bin/env bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2024 Huawei Technologies Co., Ltd. All rights reserved.

# Todo: Remove in furture
SOURCE_PACKAGE_SUFFIX=rpm
X2EPKG_CACHE_DIR=$HOME/.cache/x2epkg
X2EPKG_DEST_DIR=$X2EPKG_CACHE_DIR/convert
X2EPKG_EPKG_DIR=$X2EPKG_CACHE_DIR/epkg

EPKG_PKG_DIR=$X2EPKG_EPKG_DIR
EPKG_REPO_DIR=$X2EPKG_CACHE_DIR/repo
EPKG_REPO_PKG_INFO_DIR=$EPKG_REPO_DIR/pkg-info
EPKG_REPO_STORE_DIR=$EPKG_REPO_DIR/store
EPKG_REPO_REPODATA_DIR=$EPKG_REPO_DIR/repodata

for epkg_file in "$EPKG_PKG_DIR"/*; do
    epkg_name=$(basename $epkg_file)

    pkg_info_dir=$EPKG_REPO_PKG_INFO_DIR/${epkg_name:0:2}
    store_dir=$EPKG_REPO_STORE_DIR/${epkg_name:0:2}
    mkdir -p $pkg_info_dir
    mkdir -p $store_dir

    # pkf-info
    epkg_json_file=${epkg_name%.epkg}.json
    tar --use-compress-program=zstd -xf ${epkg_file} -O ./info/package.json --strip-components=2 > ${pkg_info_dir}/${epkg_json_file}

    # store
    cp ${epkg_file} ${store_dir}/
done

# repodata
mkdir -p $EPKG_REPO_REPODATA_DIR
tar --use-compress-program=zstd -cf ${EPKG_REPO_REPODATA_DIR}/pkg-info.zst -C ${EPKG_REPO_PKG_INFO_DIR} .

store_paths=${EPKG_REPO_REPODATA_DIR}/store-paths
> ${store_paths}
for epkg_file_tmp in "$EPKG_REPO_STORE_DIR"/*; do
    echo ${epkg_file_tmp%.*}  >> ${store_paths}
done
zstd --rm ${store_paths}

touch ${EPKG_REPO_REPODATA_DIR}/index.yaml

